<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <basic-container>
    <!--   :edit-config="{trigger: 'click', mode: 'cell',  :edit-config="editConfig"        @edit-actived="editActived" icon: 'fa fa-pencil-square-o'}"-->
    <vxe-grid
        border
        resizable
        form-config
        keep-source
        height="100%"
        ref="vGrid"
        headerAlign="center"
        :proxy-config="tableProxy"
        :toolbar="tableToolbar"
        :columns="tableColumn"
        :data="tableData"
        @cell-click="editActived"
    >
      <template v-slot:buttons>
        <template v-if="currentDay>=0&&isEdit">
          <vxe-button v-if="isEdit" @click="onClickSave">保存</vxe-button>
          <vxe-button v-if="isEdit" @click="closeEdit">取消</vxe-button>
        </template>
        <template v-if="currentDay>=0&&!isEdit">
          <vxe-button @click="openEdit">编辑</vxe-button>
        </template>

      </template>
      <!--使用 form 插槽-->
      <template v-slot:form>
        <vxe-form :data="formData" @submit="getTableData">
          <vxe-form-item title="科室">
            <el-select ref="selectWareRef" v-model="formData.wareId" @change="selectWareBean">
              <el-option
                  ref="elOptionRef"
                  v-for="(item,index) in wareList"
                  :value="item.id"
                  :label="item.name"
                  :key="item.code"
              >
              </el-option>
            </el-select>
          </vxe-form-item>
          <vxe-form-item title="值班人">
            <el-select ref="selectWareRef" v-model="formData.personRange" multiple>
              <el-option
                  ref="elOptionPersonRef"
                  v-for="(item,index) in personList"
                  :value="item.id"
                  :label="item.name"
                  :key="item.code"
              >
              </el-option>
            </el-select>
          </vxe-form-item>
          <vxe-form-item>

            <el-button type="success" plain @click="onChangeWeek('本周')" label="本周">本周</el-button>
            <el-radio-group style="margin-left: 10px">
              <span style="border-left:1px solid #DCDFE6 !important;" class="el-radio-button__inner"
                    @click="onChangeWeek('上一周')">上一周</span>
              <span class="el-radio-button__inner" @click="onChangeWeek('下一周')">下一周</span>
            </el-radio-group>

          </vxe-form-item>

          <vxe-form-item>
            <vxe-button type="submit" status="primary">查询</vxe-button>
          </vxe-form-item>

          <!--  <vxe-from-item>
              <vxe-button status="success" plain  label="本周" >快速生成</vxe-button>
            </vxe-from-item>-->
        </vxe-form>
      </template>
      <template v-slot:column_header="scop">
        <div class="first-col">
          <div class="first-col-top">{{scop.column.title}}</div>
          <div class="first-col-bottom">({{ scop.column.property}})</div>
        </div>
      </template>
      <template v-slot:default_show="scop">
        <el-tag
            :key="item.classId"
            style="color: white"
            v-for="item in scop.row[scop.column.property]"
            :color="findName(item)"
            :disable-transitions="false">
          {{ item.className }}-{{ item.limitCount }}
        </el-tag>
      </template>
      <template v-slot:edit_show="scop">
        <el-tag
            :key="item.classId"
            style="color: white"
            v-for="item in scop.row[scop.column.property]"
            :color="findName(item)"
            :disable-transitions="false">
          {{ item.className }}-{{ item.limitCount }}
        </el-tag>
        <!--        <el-select @visible-change="(e)=> visibleChange(e,scop)" v-model="classKindBean"   multiple value-key="id"  @change="(data) => selectClassKindChange(data,scop)">-->
        <!--          <el-option-->
        <!--                  v-for="item in classKindList"-->
        <!--                  :key="item.id"-->
        <!--                  :label="item.className"-->
        <!--                  :value="item">-->
        <!--          </el-option>-->
        <!--        </el-select>-->


      </template>
      <template v-slot:tool_edit="{row, rowIndex }">
        <vxe-button :loading="row.loading">操作</vxe-button>
        <!--          <template v-if="$refs.vGrid.isActiveByRow(row)">-->
        <!--            <vxe-button @click="saveRowEvent(row)" :loading="row.loading">保存</vxe-button>-->
        <!--            <vxe-button @click="cancelRowEvent(row)">取消</vxe-button>-->
        <!--          </template>-->
        <!--          <template v-else>-->
        <!--            <vxe-button @click="editRowEvent(row)">编辑</vxe-button>-->
        <!--          </template>-->
      </template>
    </vxe-grid>
    <vxe-modal v-model="showEdit" title="编辑" width="60%" destroy-on-close>
      <vxe-form @submit="editClosed">
        <vxe-form-item title="选择班次" field="role" span="24">
          <el-select @visible-change="visibleChange" v-model="classKindBean" multiple value-key="id"
                     @change="selectClassKindChange">
            <el-option
                v-for="item in classKindList"
                :key="item.id"
                :label="item.className"
                :value="item">
            </el-option>
          </el-select>

        </vxe-form-item>
        <div v-for="(item,index) in selectClassBean" :key="'li_'+item.id">
          <vxe-form-item :title="item.className" span="12" />
          <vxe-form-item title="挂号数" span="12">
            <el-input v-model="item.limitCount" @input="$forceUpdate()"></el-input>
          </vxe-form-item>
        </div>
        <vxe-form-item align="center" span="24"
                       :item-render="{ name: '$buttons', children: [{ props: { type: 'submit', content: '提交', status: 'primary' } }] }">

          <vxe-button content="提交" status="primary" @click="submit"></vxe-button>
        </vxe-form-item>

      </vxe-form>

    </vxe-modal>
  </basic-container>
</template>

<script>
import { getWeekDay } from '@/util/date'
import { findDictName } from './option'
import { wareList } from '../setting-template/option'

export default {
  name: 'ware-schedule',
  data () {
    return {
      weekNumber: '本周',
      isEdit: false,
      showEdit: false,
      editColumn: [],
      wareList: [],
      personList: [],
      currentDay: 0,
      classKindBean: [],
      selectClassBean: [],
      showDetails: false,
      selectRow: null,
      editConfig: { trigger: 'manual', mode: 'cell', showIcon: false, autoClear: false, showStatus: true },
      tableProxy: {
        autoLoad: false,
        form: true,
        props: {
          list: 'data.data',
          total: 'data.total'

        },
        ajax: {
          query: (data) => {
            // console.log(data)
            return this.$api.getDutyRecordList(this.formData)
          },
          delete: ({ body }) => this.$api.delClassKind(body),
          save: this.saveTabeData
        }
      },
      formData: {
        wareId: null,
        dateRange: [],
        personRange: null
      },
      tableData: [],
      showWeekDate: ['一', '二', '三', '四', '五', '六', '日'],
      tableColumn: [
        {
          type: 'seq',
          width: 40,
          resizable: false
        },
        {
          title: '姓名',
          field: 'personName'
        },
        {

          title: '',
          editRender: { name: 'ElSelect', autofocus: '.el-select__input' },
          slots: {
            header: 'column_header'
          }

        },
        {

          title: '',
          editRender: { name: 'ElSelect', autofocus: '.el-select__input' },
          slots: {
            header: 'column_header'
          }
        },
        {
          title: '',
          editRender: { name: 'ElSelect', autofocus: '.el-select__input' },
          slots: {
            header: 'column_header'
          }
        },
        {

          title: '',
          editRender: { name: 'ElSelect', autofocus: '.el-select__input' },
          slots: {
            header: 'column_header'
          }
        },
        {

          title: '',
          editRender: { name: 'ElSelect', autofocus: '.el-select__input' },
          slots: {
            header: 'column_header'
          }
        },
        {

          title: '',
          editRender: { name: 'ElSelect', autofocus: '.el-select__input' },
          slots: {
            header: 'column_header'
          }
        },
        {
          title: '',
          editRender: { name: 'ElSelect', autofocus: '.el-select__input' },
          slots: {
            header: 'column_header'
          }
        },
        {
          title: '操作',
          slots: {
            default: 'tool_edit'
          }
        }

      ],
      tableToolbar: {
        custom: false,
        refresh: false
      },
      classKindList: []
    }
  },
  // this.wareList.find( (item,index) =>{
  //   if( this.formData &&this.formData.wareId.toString() === item.id.toString() ){
  //     // this.$refs.vGrid.commitProxy('query')
  //     return true
  //   }
  //   return false
  // })
  created () {
    this.init()
    this.$api.getWareList().then(res => {
      this.wareList = res
      this.formData.wareId = this.wareList[0].id
      this.formData.deptId = this.wareList[0].deptId
      this.$nextTick(() => {
        let index = 0
        this.$refs.elOptionRef[index].dispatch('ElSelect', 'handleOptionClick', [this.$refs.elOptionRef[index], true])
      })
      this.getTableData()

    })
    this.$api.fetchClassKindList({
      current: 1,
      size: 9999
    }).then(res => {
      this.classKindList = res.data.data.records
    })
    // this.tableColumn[2].children[0].title = this.showWeekDate[0]

    if (this.$route.query.ware) {
      let ware = this.$route.query.ware
      this.formData.wareId = ware.wareId
    }


  },
  mounted () {

  },
  methods: {
    init (time) {
      let weekDates = getWeekDay(time)
      this.formData.dateRange = weekDates
      this.tableColumn = this.tableColumn.map((item, index) => {
        console.log('index', index)
        if (index > 1 && index < this.tableColumn.length - 1) {
          item.title = '星期' + this.showWeekDate[index - 2]
          item.field = weekDates[index - 2]
          if (!item.slots.default) {
            item.slots.default = 'default_show'
          }
          if (!item.slots.edit) {
            item.slots.edit = 'edit_show'
          }

        }
        return item
      })


    },
    getTableData () {
      // this.$refs.vGrid.commitProxy('query')
      this.$api.getDutyRecordList(this.formData).then(res => {
        let tempData = res.data.data
        this.$api.getDoctorList({ wareId: this.formData.wareId }).then(result => {
          this.personList = result.data.data
          if (!tempData || tempData.length === 0) {
            result.data.data.forEach((item, index) => {
              this.tableData[index] = {}
              this.tableData[index].personId = item.id
              this.tableData[index].personName = item.name

            })
            this.$refs.vGrid.loadData(this.tableData)
          } else {
            this.$refs.vGrid.loadData(tempData)
          }
        })

      })

    },
    openEdit () {
      this.isEdit = true
      this.editConfig.trigger = 'click'
    },
    closeEdit () {
      this.isEdit = false
      this.editConfig.trigger = 'manual'
      let xTable = this.$refs.vGrid
      xTable.clearActived()
    },
    onClickSave () {
      this.$refs.vGrid.commitProxy('save')
      this.closeEdit()
    },
    showDetailEvent (row) {
      this.selectRow = row
      this.showDetails = true
    },
    headerClickEvent (evnt) {
      this.$XModal.alert('头部点击事件')
    },
    addressClickEvent (row) {
      this.$XModal.alert(`address点击事件：${ row.address }`)
    },
    filterSexMethod ({ option, row }) {
      return row.sex === option.data
    },
    changeFilterEvent (evnt, option, $panel) {
      option.data = evnt.target.value
      $panel.changeMultipleOption(evnt, !!option.data, option)
    },
    footerMethod ({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (['sex', 'num'].includes(column.property)) {
            return XEUtils.sum(data, column.property)
          }
          return null
        })
      ]
    },
    handleEdit (index, row) {
      console.log(index, row)
    },
    handleDelete (index, row) {
      console.log(index, row)
    },
    selectWareBean (value) {

    },
    focusClassKind (e, scop) {
      // this.classKindBean = []
      // if( scop.row[scop.column.property]){
      //   scop.row[scop.column.property].forEach(item=>{
      //     this.classKindBean.push({id: Number(item.classId)})
      //   })
      // }
    },
    blurClassKind (e, scop) {
      // let info =  scop.row[scop.column.property][0]
      // scop.row[scop.column.property]=[]
      // this.classKindBean.forEach((item,index)=>{
      //
      //   scop.row[scop.column.property].push(Object.assign({},info,{classId: item.id,className: item.className,color: item.color}))
      //
      // })
      // this.$refs.vGrid.updateStatus(scop)
    },
    visibleChange (visible, scop) {
      // 出现则为 true，隐藏则为 false
      if (visible) {

      } else {

      }
    },
    selectClassKindChange (data) {
      console.log(data)
      this.selectClassBean = Object.assign([], data)

    },
    findName (row) {
      if (row.color) {
        return row.color
      }
      let result = findDictName(this.classKindList, row.classId, { label: 'className', value: 'id' })
      let color = 'red'
      if (result) {
        color = result.color
        row.color = result.color
        row.className = result.className
      }

      return color
    },
    showValue (value) {
      console.log(value)
      return JSON.stringify(value)
    },
    onChangeWeek (value) {

      switch (value) {
      case  '本周':
        this.currentDay = 0
        this.init()
        if (this.isEdit) {
          return
        }
        this.getTableData()
        break
      case '下一周':
        this.currentDay = this.currentDay + 1
        this.init(7 * this.currentDay)
        if (this.isEdit) {
          return
        }
        this.getTableData()
        break
      case '上一周':
        if (this.isEdit && this.currentDay === 0) {
          return
        }
        this.currentDay = this.currentDay - 1
        this.init(7 * this.currentDay)
        if (this.isEdit) {
          return
        }
        this.getTableData()
        break

      }
    },
    editActived (info) {
      if (!this.isEdit) {
        return
      }
      this.editColumn = info
      let { row, rowIndex, $rowIndex, columnIndex, $columnIndex, cell } = info
      if (info.column.property && info.column.property != 'seq' && info.column.property != 'personName') {
        if (!row.wareId) {
          row.wareId = this.formData.wareId
        }
        this.selectClassBean = []
        if (row[info.column.property]) {
          this.selectClassBean = row[info.column.property].map(item1 => {
            let result = this.classKindList.find(item2 => {
              return item2.id.toString() === item1.classId.toString()
            })
            item1.id = result.id
            item1.className = result.className
            return item1
          })
        }
        this.classKindBean = Object.assign([], this.selectClassBean)
        this.showEdit = true
      }

    },
    editClosed () {
      let scop = this.editColumn
      let { row, rowIndex, $rowIndex, columnIndex, $columnIndex, cell } = scop
      if (scop.column.property && scop.column.property != 'seq' && scop.column.property != 'personName') {
        let info = {}
        if (!scop.row[scop.column.property] || scop.row[scop.column.property].length === 0) {
          scop.row[scop.column.property] = []
        } else {
          info = Object.assign({}, scop.row[scop.column.property][0])
        }
        scop.row[scop.column.property] = []
        this.selectClassBean.forEach((item, index) => {

          scop.row[scop.column.property].push(Object.assign({}, info, {
            classId: item.id,
            className: item.className,
            color: item.color,
            limitCount: item.limitCount
          }))

        })
      }
      this.showEdit = false
    },
    editRowEvent (row) {
      this.$refs.vGrid.setActiveRow(row)
    },
    saveTabeData (data) {
      console.log(data)
      let { body } = data
      let submitData = []

      if (body.insertRecords.length > 0 && body.updateRecords.length === 0) {

      }
      if (body.updateRecords.length > 0) {

        return this.$api.putBatchDutyRecord(body.updateRecords)

      }
      return new Promise((resolve, reject) => {
        reject({ code: 500, msg: 'error' })
      })
    },
    saveRowEvent (row) {
      this.$refs.vGrid.clearActived().then(() => {
        let xTable = this.$refs.vGrid
        if (xTable.isUpdateByRow(row)) {
          row.loading = true
          // 局部保存，并将行数据恢复到初始状态（如果 record 为空则不改动行数据，只恢复状态）
          let submitData = []
          let tempObj = {
            wareId: this.formData.wareId,
            personName: row[this.tableColumn[1].field],
            personId: row.personId
          }
          let newData = Object.assign({}, tempObj)
          this.tableColumn.forEach((column, index) => {
            if (index > 0) {
              let name = column.field
              if (Array.isArray(row[name])) {
                newData[name] = row[name].slice() //Object.assign([],row[field])
                row[name].forEach(item => {
                  submitData.push(Object.assign({ dutyDate: name }, tempObj, { classId: item.classId, id: item.id }))
                })
              }
            }

          })
          this.$api.putBatchDutyRecord(submitData).then(res => {
            xTable.reloadRow(row, newData, null)
            this.$XModal.message({ message: '保存成功！', status: 'success' })

          }).finally(() => {
            row.loading = false
          })
          // this.submitSave(row).then(data => {
          //
          //
          // })
        } else {
          this.$XModal.message({ message: '数据未改动！', status: 'info' })
        }
      })
    },
    cancelRowEvent (row) {
      let xTable = this.$refs.vGrid
      xTable.clearActived()
        .then(() => xTable.revertData(row))
    }
  }
}
</script>

<style scoped>
  .first-col-bottom {
    font-size: 12px;
    color: #ffb200;
  }
</style>
